package com.ctrip.corp.obt.shard.sql.mybatis.interceptor.compatibility.dm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.compatibility.BaseSemanticCompatibility;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.OrderByElement;
import net.sf.jsqlparser.statement.select.SelectItem;

import static com.ctrip.corp.obt.shard.sql.mybatis.interceptor.compatibility.constant.CompatibilityConstant.PRIMARY_KEY_ID;
import static com.ctrip.corp.obt.shard.sql.mybatis.interceptor.compatibility.constant.CompatibilityConstant.VLAUE_NULL;

/**
 * sql语义兼容
 *
 * @author x.shen
 * @since 2023/11/26
 */
@Slf4j
public class DMSemanticCompatibility extends BaseSemanticCompatibility {
    /**
     * sql关键字集合
     */
    public static final Set<String> SQL_KEY_WORDS = new HashSet<>();

    /**
     * 待兼容关键字存放
     */
    public DMSemanticCompatibility() {
        SQL_KEY_WORDS.add("level");
    }

    /**
     * 前置处理
     * 1.处理引号
     *
     * @param sql
     * @return
     */
    public String preHandleSql(String sql) {
        // 处理引号
        String result = handleQuotes(sql);
        return result;
    }

    public boolean handleUpdatePrimaryKey(Column column, Expression expression) {
        if (PRIMARY_KEY_ID.equalsIgnoreCase(column.getColumnName())) {
            // set id = id
            if (expression instanceof Column && PRIMARY_KEY_ID.equalsIgnoreCase(((Column)expression).getColumnName())) {
                return true;
            } else if (expression instanceof NullValue && VLAUE_NULL.equalsIgnoreCase(expression.toString())) {
                return true;
            }
        }
        return false;
    }
}
